import React from 'react'
import { Route, Redirect, Switch } from 'react-router-dom'

const renderRoutes = (routes, authed, authPath = '/login', extraProps = {}, switchProps = {}) => {

  const newRoutes = [];

  const setRoutes = (routes)=>{
    routes.forEach(r =>{
      newRoutes.push(r);
      if(r.routes){
        setRoutes(r.routes);
      }
    })
  }
  setRoutes(routes[0].routes);
  
  // console.log(newRoutes);

  return (
    <Switch {...switchProps}>
      {routes.map((route, i) => {
        return (
          <Route
            key={route.key || i}
            path={route.path}
            exact={route.exact}
            strict={route.strict}
            render={(props) => {

              let {pathname} = props.location;

              const findObj = newRoutes.find(v =>getPath(v.path) === getPath(pathname));
              // console.log(findObj)
              // console.log(props)
              if(!findObj) {
                return <Redirect to={{ pathname: '/404', state: { from: props.location } }} />
              }

              const {requiresAuth,path} = findObj;
              
              if (!requiresAuth || authed || path === authPath) {
                return <route.component {...props} {...extraProps} route={route} />
              }
              return <Redirect to={{ pathname: authPath, state: { from: props.location } }} />
            }}
          />
        )
      })}
    </Switch>
  )
} 

export default renderRoutes



function getPath(str){
  return '/'+str.split('/')[1]
}